import hashlib, re

import django.forms as forms
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ValidationError
import django.http as http
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth import logout as auth_logout
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
    
from django_community.models import UserOpenID, UserProfile
from django_community.config import PROFILE_BUILDER

def openid_logout(request):
    request.session['openids'] = []
    
def handle_logout(request):
    auth_logout(request)
    
def get_logged_user(request):
    """
    Returns the current user who is logged in, checks for openid user first, then for regular user, return None if no user is currently logged in
    """
    if settings.OPENID_ENABLED and hasattr(request, 'openid'):
        user = UserOpenID.objects.get_for_openid(request, request.openid)
    if not user:
        user = request.user
    return user
        
def handle_signup(request,  data):
    error = None
    username = data['username']
    email = data['email']
    password = hashlib.sha256(data['password']).hexdigest()
    
    try:
        existing_user = models.User.objects.get(username = username,  email = email)
        error = 'username or email taken'
    except ObjectDoesNotExist:
        new_user = models.User(username = username,  email = email,  password = password, display_name = username)
        new_user.save()
        
    request.session['user_id']  = new_user.id
    return new_user,  error
    
def handle_edit_profile(user,  data):
    user.display_name = data.get('display_name',  user.display_name)
    user.email = data.get('email',  user.email)
    user.first_name = data.get('first_name',  user.first_name)
    user.last_name = data.get('last_name',  user.last_name)
    user.location = data.get('location',  user.location)
    user.website = data.get('website',  user.website)
    user.birthdate = data.get('birthday', user.birthdate)
    user.about_me = data.get('about_me',  user.about_me)
    user.save()

def get_or_create_from_openid(openid):
    try:
        user = models.User.objects.get(username = openid)
    except ObjectDoesNotExist:
        password = hashlib.sha256(openid).hexdigest()
        user = models.User(username = openid,  email = '',  password = password)
        user.save()
        user.display_name = "%s_%s" % ('user',  str(user.id))
        user.save()
    
    return user

def generate_random_user_name():
    import random
    
    current_users = User.objects.all().order_by('-id')
    if current_users:
        next_id = current_users[0].id + 1
    else:
        next_id = 1
    random_salt = random.randint(1, 5000)
    return 'user_%s_%s' % (str(next_id), str(random_salt))

def create_user_from_openid(request, openid):
    from django_community.config import OPENID_FIELD_MAPPING
    from django_utils.request_helpers import get_ip
    
    username = generate_random_user_name()
    profile_attributes = {}
    for attribute in OPENID_FIELD_MAPPING.keys():
        mapped_attribute = OPENID_FIELD_MAPPING[attribute]
        if openid.sreg and openid.sreg.get(attribute, ''):
            profile_attributes[mapped_attribute] = openid.sreg.get(attribute, '')
            
    new_user = User(username = username)
    new_user.save()
    new_openid = UserOpenID(openid = openid.openid, user = new_user)
    new_openid.save()
    new_user_profile = UserProfile(user = new_user)
    for filled_attribute in profile_attributes.keys():
        setattr(new_user, filled_attribute, profile_attributes[filled_attribute])
    new_user_profile.save()
    return new_user

def get_anon_user(request):
    try:
        anon_user = User.objects.get(username = generate_anon_user_name(request))
    except ObjectDoesNotExist:
        anon_user = create_anon_user(request)
    return anon_user
    
def create_anon_user(request):
    anon_user_name = generate_anon_user_name(request)
    anon_user = User(username = anon_user_name)
    anon_user.save()
    user_profile = UserProfile(user = anon_user, display_name = 'anonymous')
    user_profile.save()
    return anon_user

def generate_anon_user_name(request):
    from django_utils.request_helpers import get_ip
    
    ip = get_ip(request)
    return "anon_user_%s" % (str(ip))

def is_anon_user(user):
    return user.username[0:10] == 'anon_user_'

def process_ax_data(user, ax_data):
    import django_openidconsumer.config
     
    emails = ax_data.get(django_openidconsumer.config.EMAIL.get('type_uri', ''), '')
    display_names = ax_data.get(django_openidconsumer.config.ALIAS.get('type_uri', ''), '')
    if emails and not user.email.strip():
        user.email = emails[0]
        user.save()
    if not user.linked_profile.display_name.strip():
        if display_names:
            user.linked_profile.display_name = display_names[0]
        elif emails:
            user.linked_profile.display_name = emails[0].split('@')[0]
        user.linked_profile.save()